import { NextRequest, NextResponse } from 'next/server';
import {
  Document,
  Paragraph,
  TextRun,
  HeadingLevel,
  AlignmentType,
  BorderStyle,
  Packer,
  Header,
  Footer,
  PageNumber,
} from 'docx';
import UserModel from '@/models/user';

// 定义颜色常量
const THEME_COLOR = '4472C4';
const THEME_COLOR_LIGHT = 'E6EBF5';
const THEME_COLOR_DARK = '2F5597';
const GRAY_COLOR = '767171';

export async function GET(request: NextRequest) {
  try {
    // 从URL参数中获取用户ID
    const url = new URL(request.url);
    const userId = url.searchParams.get('userId');

    if (!userId) {
      return NextResponse.json({ error: '缺少用户ID参数' }, { status: 400 });
    }

    // 获取用户信息
    const user = await UserModel.findById(parseInt(userId));
    if (!user) {
      return NextResponse.json({ error: '用户不存在' }, { status: 404 });
    }

    // 获取用户的教育经历、工作经历、技能等
    const educationExperiences = await UserModel.getEducationExperiences(parseInt(userId));
    const workExperiences = await UserModel.getWorkExperiences(parseInt(userId));
    const skills = await UserModel.getSkills(parseInt(userId));

    // 尝试获取实习经历和获奖情况
    let internships = [];
    let awards = [];

    try {
      const [internshipsResult] = await UserModel.query<any[]>(
        'SELECT * FROM internships WHERE user_id = ? ORDER BY created_at DESC',
        [userId]
      );
      internships = Array.isArray(internshipsResult) ? internshipsResult : [];
    } catch (error) {
      console.error('获取实习经历失败:', error);
    }

    try {
      const [awardsResult] = await UserModel.query<any[]>(
        'SELECT * FROM awards WHERE user_id = ? ORDER BY date DESC',
        [userId]
      );
      awards = Array.isArray(awardsResult) ? awardsResult : [];
    } catch (error) {
      console.error('获取获奖情况失败:', error);
    }

    // 创建Word文档
    const doc = new Document({
      styles: {
        paragraphStyles: [
          {
            id: "Normal",
            name: "Normal",
            run: {
              size: 24, // 12pt
              font: "Calibri",
            },
            paragraph: {
              spacing: {
                line: 360, // 1.5 倍行距
              },
            },
          },
          {
            id: "Heading1",
            name: "Heading 1",
            basedOn: "Normal",
            next: "Normal",
            run: {
              size: 32, // 16pt
              bold: true,
              color: THEME_COLOR,
              font: "Calibri",
            },
            paragraph: {
              spacing: {
                before: 240, // 12pt
                after: 120, // 6pt
              },
              border: {
                bottom: {
                  color: THEME_COLOR,
                  space: 1,
                  style: BorderStyle.SINGLE,
                  size: 6,
                },
              },
            },
          },
          {
            id: "Heading2",
            name: "Heading 2",
            basedOn: "Normal",
            next: "Normal",
            run: {
              size: 28, // 14pt
              bold: true,
              color: THEME_COLOR_DARK,
              font: "Calibri",
            },
            paragraph: {
              spacing: {
                before: 240, // 12pt
                after: 120, // 6pt
              },
            },
          },
          {
            id: "Title",
            name: "Title",
            basedOn: "Normal",
            next: "Normal",
            run: {
              size: 40, // 20pt
              bold: true,
              color: THEME_COLOR_DARK,
              font: "Calibri",
            },
            paragraph: {
              spacing: {
                before: 240, // 12pt
                after: 240, // 12pt
              },
              alignment: AlignmentType.CENTER,
            },
          },
        ],
      },
      sections: [{
        properties: {
          page: {
            margin: {
              top: 1133, // 2cm
              right: 1133, // 2cm
              bottom: 1133, // 2cm
              left: 1133, // 2cm
            },
          },
        },
        headers: {
          default: new Header({
            children: [
              new Paragraph({
                alignment: AlignmentType.RIGHT,
                children: [
                  new TextRun({
                    text: `${user.username} 的个人简历`,
                    size: 20,
                    color: GRAY_COLOR,
                  }),
                ],
              }),
            ],
          }),
        },
        footers: {
          default: new Footer({
            children: [
              new Paragraph({
                alignment: AlignmentType.CENTER,
                children: [
                  new TextRun({
                    children: [PageNumber.CURRENT],
                    size: 20,
                    color: GRAY_COLOR,
                  }),
                  new TextRun({
                    text: " / ",
                    size: 20,
                    color: GRAY_COLOR,
                  }),
                  new TextRun({
                    children: [PageNumber.TOTAL_PAGES],
                    size: 20,
                    color: GRAY_COLOR,
                  }),
                ],
              }),
            ],
          }),
        },
        children: [
          // 标题
          new Paragraph({
            text: `${user.username} 的个人简历`,
            heading: HeadingLevel.TITLE,
            alignment: AlignmentType.CENTER,
            spacing: {
              after: 400,
            },
          }),

          // 个人信息
          new Paragraph({
            text: '个人信息',
            heading: HeadingLevel.HEADING_1,
          }),

          // 使用简单段落替代表格
          new Paragraph({
            children: [
              new TextRun({
                text: '姓名：',
                bold: true,
              }),
              new TextRun(user.username || ''),
              new TextRun({
                text: '    电话：',
                bold: true,
              }),
              new TextRun(user.phone || ''),
              new TextRun({
                text: '    邮箱：',
                bold: true,
              }),
              new TextRun(user.email || ''),
            ],
            spacing: {
              after: 200,
            },
          }),

          new Paragraph({
            children: [
              new TextRun({
                text: '所在地：',
                bold: true,
              }),
              new TextRun(user.location || ''),
              new TextRun({
                text: '    出生日期：',
                bold: true,
              }),
              new TextRun(user.birth_date ? new Date(user.birth_date).toLocaleDateString('zh-CN') : ''),
              new TextRun({
                text: '    单位：',
                bold: true,
              }),
              new TextRun(user.company || ''),
            ],
            spacing: {
              after: 200,
            },
          }),

          // 个人综述
          ...(user.resume_title || user.resume_description ? [
            new Paragraph({
              text: '个人综述',
              heading: HeadingLevel.HEADING_1,
              spacing: {
                before: 400,
              },
            }),
            ...(user.resume_title ? [
              new Paragraph({
                children: [
                  new TextRun({
                    text: user.resume_title,
                    bold: true,
                    size: 28,
                  }),
                ],
                spacing: {
                  after: 120,
                },
              }),
            ] : []),
            ...(user.resume_description ? [
              new Paragraph({
                text: user.resume_description,
                spacing: {
                  after: 240,
                },
              }),
            ] : []),
          ] : []),

          // 教育经历
          ...(educationExperiences.length > 0 ? [
            new Paragraph({
              text: '教育经历',
              heading: HeadingLevel.HEADING_1,
              spacing: {
                before: 400,
              },
            }),

            ...educationExperiences.map(edu => {
              return [
                new Paragraph({
                  children: [
                    new TextRun({
                      text: `${edu.school}`,
                      bold: true,
                      size: 28,
                    }),
                  ],
                  spacing: {
                    before: 240,
                    after: 120,
                  },
                }),
                new Paragraph({
                  children: [
                    new TextRun({
                      text: `${edu.degree}${edu.field_of_study ? ` · ${edu.field_of_study}` : ''}`,
                      size: 26,
                    }),
                    new TextRun({
                      text: ` | ${edu.start_date ? new Date(edu.start_date).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long' }) : ''} - ${edu.end_date ? new Date(edu.end_date).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long' }) : '至今'}`,
                      italics: true,
                      color: GRAY_COLOR,
                    }),
                  ],
                  spacing: {
                    after: 120,
                  },
                }),
                ...(edu.description ? [
                  new Paragraph({
                    text: edu.description,
                    spacing: {
                      after: 240,
                    },
                  }),
                ] : []),
              ];
            }).flat(),
          ] : []),

          // 工作经历
          ...(workExperiences.length > 0 ? [
            new Paragraph({
              text: '工作经历',
              heading: HeadingLevel.HEADING_1,
              spacing: {
                before: 400,
              },
            }),

            ...workExperiences.map(work => {
              return [
                new Paragraph({
                  children: [
                    new TextRun({
                      text: `${work.company_name || work.company || ''}`,
                      bold: true,
                      size: 28,
                    }),
                  ],
                  spacing: {
                    before: 240,
                    after: 120,
                  },
                }),
                new Paragraph({
                  children: [
                    new TextRun({
                      text: `${work.position}`,
                      size: 26,
                    }),
                    new TextRun({
                      text: ` | ${work.start_date ? new Date(work.start_date).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long' }) : ''} - ${work.end_date ? new Date(work.end_date).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long' }) : '至今'}`,
                      italics: true,
                      color: GRAY_COLOR,
                    }),
                  ],
                  spacing: {
                    after: 120,
                  },
                }),
                ...(work.description ? [
                  new Paragraph({
                    text: work.description,
                    spacing: {
                      after: 240,
                    },
                  }),
                ] : []),
              ];
            }).flat(),
          ] : []),

          // 实习经历
          ...(internships.length > 0 ? [
            new Paragraph({
              text: '实习经历',
              heading: HeadingLevel.HEADING_1,
              spacing: {
                before: 400,
              },
            }),

            ...internships.map(internship => {
              return [
                new Paragraph({
                  children: [
                    new TextRun({
                      text: `${internship.company}`,
                      bold: true,
                      size: 28,
                    }),
                  ],
                  spacing: {
                    before: 240,
                    after: 120,
                  },
                }),
                new Paragraph({
                  children: [
                    new TextRun({
                      text: `${internship.position}`,
                      size: 26,
                    }),
                    new TextRun({
                      text: ` | ${internship.period || ''}`,
                      italics: true,
                      color: GRAY_COLOR,
                    }),
                  ],
                  spacing: {
                    after: 120,
                  },
                }),
                ...(internship.description ? [
                  new Paragraph({
                    text: internship.description,
                    spacing: {
                      after: 240,
                    },
                  }),
                ] : []),
              ];
            }).flat(),
          ] : []),

          // 专业技能
          ...(skills.length > 0 ? [
            new Paragraph({
              text: '专业技能',
              heading: HeadingLevel.HEADING_1,
              spacing: {
                before: 400,
              },
            }),

            ...skills.map(skill => {
              const proficiencyText = skill.proficiency === 1 ? '入门' : skill.proficiency === 2 ? '基本' : '精通';
              return new Paragraph({
                children: [
                  new TextRun({
                    text: `• ${skill.name}`,
                    bold: true,
                  }),
                  new TextRun({
                    text: ` (${proficiencyText})`,
                    italics: true,
                  }),
                  ...(skill.description ? [
                    new TextRun({
                      text: `: ${skill.description}`,
                    }),
                  ] : []),
                ],
                spacing: {
                  after: 120,
                },
              });
            }),
          ] : []),

          // 获奖情况
          ...(awards.length > 0 ? [
            new Paragraph({
              text: '获奖情况',
              heading: HeadingLevel.HEADING_1,
              spacing: {
                before: 400,
              },
            }),

            ...awards.map(award => {
              return [
                new Paragraph({
                  children: [
                    new TextRun({
                      text: `${award.name}`,
                      bold: true,
                      size: 28,
                    }),
                  ],
                  spacing: {
                    before: 240,
                    after: 120,
                  },
                }),
                new Paragraph({
                  children: [
                    new TextRun({
                      text: `${award.issuer}`,
                      size: 26,
                    }),
                    new TextRun({
                      text: ` | ${award.date || ''}`,
                      italics: true,
                      color: GRAY_COLOR,
                    }),
                  ],
                  spacing: {
                    after: 120,
                  },
                }),
                ...(award.description ? [
                  new Paragraph({
                    text: award.description,
                    spacing: {
                      after: 240,
                    },
                  }),
                ] : []),
              ];
            }).flat(),
          ] : []),

          // 结尾
          new Paragraph({
            children: [
              new TextRun({
                text: "简历生成于 ",
                italics: true,
                color: GRAY_COLOR,
                size: 20,
              }),
              new TextRun({
                text: new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' }),
                italics: true,
                color: GRAY_COLOR,
                size: 20,
              }),
              new TextRun({
                text: " · 校友宝平台",
                italics: true,
                color: GRAY_COLOR,
                size: 20,
              }),
            ],
            alignment: AlignmentType.CENTER,
            spacing: {
              before: 800,
            },
          }),
        ],
      }],
    });

    // 生成Word文档的Buffer
    const buffer = await Packer.toBuffer(doc);

    // 设置响应头，使浏览器下载文件
    const headers = new Headers();
    headers.set('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    headers.set('Content-Disposition', `attachment; filename=${encodeURIComponent(user.username)}_resume.docx`);

    return new NextResponse(buffer, {
      status: 200,
      headers,
    });

  } catch (error) {
    console.error('导出简历错误:', error);
    return NextResponse.json(
      { error: '导出简历失败，请稍后再试', details: error instanceof Error ? error.message : '未知错误' },
      { status: 500 }
    );
  }
}
